package demo3;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * 新第三方加密解密组件（适配者：接口与旧系统不一致，但性能好、安全性高）
 * 方法命名、参数格式与旧接口不同（如加密方法名是desEncrypt，参数含Key对象）
 */
public class NewCryptoLibrary {
    // 新组件加密方法：参数为明文、密钥对象，返回Base64编码的加密串
    public String desEncrypt(String plainText, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        System.out.println("新组件DES加密完成（性能优、安全）");
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 新组件解密方法：参数为加密串、密钥对象，返回明文
    public String desDecrypt(String cipherText, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        System.out.println("新组件DES解密完成");
        return new String(decryptedBytes, "UTF-8");
    }

    // 新组件工具方法：将字符串密钥转为Key对象（旧接口无此步骤）
    public Key generateKey(String keyStr) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(keyStr.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        return keyFactory.generateSecret(desKeySpec);
    }
}
